package 替换空格;

public class Solution
{
    public String replaceSpace(StringBuffer str)
    {
        //判断输入
        if(str==null||str.length()==0)
            return "";

        int numOfSpace=0;
        for (int i = 0; i < str.length(); i++)
        {
            if (str.charAt(i)==' ')
                numOfSpace++;
        }

        int oldlength=str.length();
        int newlength=oldlength+numOfSpace*2;

        str.setLength(newlength);

        //指针
        int p1=oldlength-1;
        int p2=newlength-1;

        while (p1>=0&&p2>p1)
        {
            if (str.charAt(p1)==' ')
            {
                str.setCharAt(p2--,'0');
                str.setCharAt(p2--,'2');
                str.setCharAt(p2--,'%');
            }
            else
            {
                str.setCharAt(p2--,str.charAt(p1));
            }
            --p1;
        }
        return str.toString();
    }

    public static void main(String[] args)
    {
        StringBuffer str = new StringBuffer("we are happy");
        Solution solution = new Solution();
        System.out.println(solution.replaceSpace(str));

    }
}
